<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/28
 * Time: 11:35
 */

namespace app\admin\controller;


use app\common\model\Bankroll;
use app\common\model\CapitalFlow;
use app\common\model\Jewel;
use app\common\model\Recharge;
use app\common\model\RechargeConfig;
use app\common\model\UserAccount;
use app\common\service\App;
use think\Db;
use think\Exception;
use think\Loader;

class Money extends Base
{

    protected $status = [
        1 => ['status' => '0' ,'msg' => '全部'],
        2 => ['status' => '2' ,'msg' => '待审核'],
//        3 => ['status' => '3' ,'msg' => '提现处理中'],
        4 => ['status' => '4' ,'msg' => '驳回'],
        5 => ['status' => '5' ,'msg' => '提现成功'],
    ];


    /**
     * 流水类型
     */
    protected $stream_status = [
        1 => ['key' => '1' ,'val' => '平台流水'],
        2 => ['key' => '2' ,'val' => '用户充值'],
        3 => ['key' => '3' ,'val' => '用户提现'],
    ];




    /**
     * 充值记录列表
     */
    public function index()
    {
        $where = [];
        if (!empty($_GET['status'])) $where['a.status']  = input('get.status');
        if (!empty($_GET['nick_name'])) $where['u.nick_name']  = ['like','%'.trim(input('get.nick_name')).'%'];
        $where['a.type'] = 1;
        $model = new Bankroll();

        if (is_numeric(input('uuid'))){
            $where['u.uuid'] =  ['like','%'.trim(input('get.uuid')).'%'];
        }
        if (is_numeric(input('trade_type'))){
            $where['a.trade_type'] =  input('trade_type');
        }
        if(!empty($_GET['startDate'])){
            $startDate=strtotime(trim(input('get.startDate')));
        }
        if(!empty($_GET['endDate'])){
            $endDate=strtotime(trim(input('get.endDate')));
        }
        if($startDate&&$endDate){
            $where['a.create_time']=['between time',[$startDate,$endDate]];
        }else if($startDate&&empty($endDate)){
            $where['a.create_time']=['> time',$startDate];
        }else if($endDate&&empty($startDate)){
            $where['a.create_time']=['< time',$endDate];
        }



        $rows  = $model->cashList($where);
        $total = $model->alias('a')
            ->join('users u','u.user_id = a.user_id','LEFT')
            ->join('user_account ac','ac.account_id = a.account_id','LEFT')
            ->where($where)
            ->sum('a.money');
        $where['a.trade_type'] = 8;
        $all = $model->alias('a')
            ->join('users u','u.user_id = a.user_id','LEFT')
            ->join('user_account ac','ac.account_id = a.account_id','LEFT')
            ->where($where)
            ->sum('a.money');


        $this->assign([
            'title' => '充值记录',
            'rows' => $rows,
            'pageHTML' => $rows->render(),
            'total' => $total,
            'all' => $all
        ]);
        return view();
    }

    /**
     * 充值详情
     */
    public function detail2()
    {
        $model = new Bankroll();
        $where['a.b_id'] = input('id');
        $data = $model->getDetail($where);
        $this->assign([
            'data' => $data,
            'title' => '充值',
            'status' => $this->status,
        ]);
        return view();
    }


    /**
     * 提现申请列表
     */
//    public function cash()
//    {
//        $where = [];
//        if (!isEmpty($_GET['status'])){
//            if ($_GET['status'] != 0){
//                $where['a.status']  = input('get.status');
//            }
//        }else{
//            $where['a.status']  = 2;
//        }
//
//        if (!empty($_GET['nick_name'])) $where['u.nick_name'] = ['like','%'.trim(input('get.nick_name')).'%'];
//        $where['a.type'] = 2;
//
//
//        if (is_numeric(input('uuid'))){
//            $map['u.uuid'] =  ['like','%'.trim(input('get.uuid')).'%'];
//        }
//
//        if(!empty($_GET['startDate'])){
//            $startDate=strtotime(trim(input('get.startDate')));
//        }
//        if(!empty($_GET['endDate'])){
//            $endDate=strtotime(trim(input('get.endDate')));
//        }
//        if($startDate&&$endDate){
//            $where['a.create_time']=['between time',[$startDate,$endDate]];
//        }else if($startDate&&empty($endDate)){
//            $where['a.create_time']=['> time',$startDate];
//        }else if($endDate&&empty($startDate)){
//            $where['a.create_time']=['< time',$endDate];
//        }
//
//        $model = new Bankroll();
//
//        if (input('download') == 'download'){ //点击了下载
//            /* 永不超时 */
//            ini_set('max_execution_time', 0);
//            //仅支付宝
//            $where['ac.type'] = 2;
//            $rows = $model->downloadList($where);
//            //         $path = ROOT_PATH.'public'.DS.'download'.DS.'excel'; //找到当前脚本所在路径
//            Loader::import('PHPExcel.PHPExcel');//手动引入PHPExcel.php
////         Loader::import('PHPExcel.PHPExcel.IOFactory.PHPExcel_IOFactory');//引入IOFactory.php 文件里面的PHPExcel_IOFactory这个类
//            $PHPExcel = new \PHPExcel();//实例化
//            $PHPSheet = $PHPExcel->getActiveSheet();
//            $PHPSheet->setTitle("提现申请".date('Ymdhis')); //给当前活动sheet设置名称
//
//            //处理表头标题
//            $PHPSheet->mergeCells('A1:E1');//合并单元格（如果要拆分单元格是需要先合并再拆分的，否则程序会报错）
//            $PHPSheet->setCellValue('A1','支付宝批量付款文件模板（前面两行请勿删除）');
////            $PHPSheet->getStyle('A1')->getFont()->setBold(true);
//            $PHPSheet->getStyle('A1')->getFont()->setSize(12);
//            $PHPSheet->getStyle('A1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
//            $PHPSheet->getStyle('A1')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
//            $PHPSheet->getColumnDimension('A')->setWidth(30);//设置列宽度
//            $PHPSheet->getColumnDimension('B')->setWidth(30);//设置列宽度
//            $PHPSheet->getColumnDimension('C')->setWidth(20);//设置列宽度
//            $PHPSheet->getColumnDimension('D')->setWidth(30);//设置列宽度
//            $PHPSheet->getColumnDimension('E')->setWidth(30);//设置列宽度
//            $PHPSheet->setCellValue("A2","序号（必填）")//表格数据
//            ->setCellValue("B2","收款方支付宝账号（必填）")
//                ->setCellValue("C2","收款方姓名（必填）")
//                ->setCellValue("D2","金额（必填，单位：元）")
//                ->setCellValue("E2","备注（选填）");
//            if (empty($rows)) $this->error('暂无数据');
//            $i = 2;
//            foreach ($rows as $k => $v){
//                $i++;
//                $PHPSheet->setCellValue("A$i",date('YmdHis').session('user_id').$i)
//                    ->setCellValue("B$i",$v['account'])
//                    ->setCellValue("C$i",$v['real_name'])
//                    ->setCellValue("D$i",div($v['money']))
//                    ->setCellValue("E$i",'');
//            }
//            $PHPWriter = \PHPExcel_IOFactory::createWriter($PHPExcel,"Excel2007");//创建生成的格式
//            $date = date('Ymdhis');
//            header('Content-Disposition: attachment;filename="提现申请'.$date.'.xlsx"');//下载下来的表格名
//            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
//            $PHPWriter->save("php://output"); //表示在$path路径下面生成demo.xlsx文件
//            exit;
//
//        }
//
//        $rows  = $model->cashList($where);
//
//        $total = $model->alias('a')
//                ->join('users u','u.user_id = a.user_id','LEFT')
//                ->join('user_account ac','ac.account_id = a.account_id','LEFT')
//                ->where($where)
//                ->sum('a.money');
//
//        $this->assign([
//            'getStatus' => $where['a.status'],
//            'title' => '提现申请列表',
//            'rows' => $rows,
//            'pageHTML' => $rows->render(),
//            'status' => $this->status,
//            'total' => $total,
//        ]);
//        return view();
//    }

    public function cash()
    {
        $where = [];
        if (!isEmpty($_GET['status'])){
            if ($_GET['status'] != 0){
                $where['a.status']  = input('get.status');
            }
        }else{
            $where['a.status']  = 2;
        }

        if (!empty($_GET['nick_name'])) $where['u.nick_name'] = ['like','%'.trim(input('get.nick_name')).'%'];
        $where['a.type'] = 2;


        if (is_numeric(input('uuid'))){
            $map['u.uuid'] =  ['like','%'.trim(input('get.uuid')).'%'];
        }

        if(!empty($_GET['startDate'])){
            $startDate=strtotime(trim(input('get.startDate')));
        }
        if(!empty($_GET['endDate'])){
            $endDate=strtotime(trim(input('get.endDate')));
        }
        if($startDate&&$endDate){
            $where['a.create_time']=['between time',[$startDate,$endDate]];
        }else if($startDate&&empty($endDate)){
            $where['a.create_time']=['> time',$startDate];
        }else if($endDate&&empty($startDate)){
            $where['a.create_time']=['< time',$endDate];
        }

        $model = new Bankroll();

        if (input('download') == 'download'){ //点击了下载
            /* 永不超时 */
            ini_set('max_execution_time', 0);
            //仅支付宝
            $where['ac.type'] = 2;
            $rows = $model->downloadList($where);
            //         $path = ROOT_PATH.'public'.DS.'download'.DS.'excel'; //找到当前脚本所在路径
            Loader::import('PHPExcel.PHPExcel');//手动引入PHPExcel.php
//         Loader::import('PHPExcel.PHPExcel.IOFactory.PHPExcel_IOFactory');//引入IOFactory.php 文件里面的PHPExcel_IOFactory这个类
            $PHPExcel = new \PHPExcel();//实例化
            $PHPSheet = $PHPExcel->getActiveSheet();
            $PHPSheet->setTitle("提现申请".date('Ymdhis')); //给当前活动sheet设置名称

            //处理表头标题
//            $PHPSheet->mergeCells('A1:E1');//合并单元格（如果要拆分单元格是需要先合并再拆分的，否则程序会报错）
//            $PHPSheet->setCellValue('A1','支付宝批量付款文件模板（前面两行请勿删除）');
//            $PHPSheet->getStyle('A1')->getFont()->setBold(true);
//            $PHPSheet->getStyle('A1')->getFont()->setSize(12);
//            $PHPSheet->getStyle('A1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
//            $PHPSheet->getStyle('A1')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPSheet->getColumnDimension('A')->setWidth(30);//设置列宽度
            $PHPSheet->getColumnDimension('B')->setWidth(30);//设置列宽度
            $PHPSheet->getColumnDimension('C')->setWidth(20);//设置列宽度
            $PHPSheet->getColumnDimension('D')->setWidth(30);//设置列宽度
            $PHPSheet->getColumnDimension('E')->setWidth(30);//设置列宽度
            $PHPSheet->setCellValue("A1","ID")//表格数据
            ->setCellValue("B1","MIYOID")
                ->setCellValue("C1","用户昵称")
                ->setCellValue("D1","姓名")
                ->setCellValue("E1","账号")
                ->setCellValue("F1","提现金额(元)")
                ->setCellValue("G1","税后金额")
                ->setCellValue("H1","提现方式")
                ->setCellValue("I1","状态")
                ->setCellValue("J1","提现申请时间");
            if (empty($rows)) $this->error('暂无数据');
            $i = 1;
            foreach ($rows as $k => $v){

                if ($v['remark'] == 'gift_coin'){

                    if ($v['use_card'] == 1){
                        $v['ratio'] = 0;
                        $v['ratio_money'] = '提现免税卡使用';
                        $v['cash']  = $v['money'];
                    }else{
                        //礼物收益需扣税
                        $cashRatio = \app\api\controller\Base::getExtend('cash_ratio');
                        $ratio = bcdiv($cashRatio,100,2);
                        $v['ratio'] = $cashRatio;
                        //提现手续费
                        $v['ratio_money'] = bcmul($ratio,$v['money'],2);
                        $v['cash'] = $v['money'] - $v['ratio_money'];
                    }


                }else{
                    $v['ratio'] = 0;
                    $v['ratio_money'] = 0;
                    $v['cash']  = $v['money'];
                }

                $i++;
                $PHPSheet->setCellValue("A$i",$v['b_id'])
                    ->setCellValue("B$i",$v['uuid'])
                    ->setCellValue("C$i",$v['nick_name'])
                    ->setCellValue("D$i",$v['real_name'])
                    ->setCellValue("E$i",$v['account'])
                    ->setCellValue("F$i",div($v['money']))
                    ->setCellValue("G$i",div($v['cash']))
                    ->setCellValue("H$i",$v['ac_type_text'])
                    ->setCellValue("I$i",$this->status[$v['status']]['msg'])
                    ->setCellValue("J$i",$v['create_time']);
            }
            $PHPWriter = \PHPExcel_IOFactory::createWriter($PHPExcel,"Excel2007");//创建生成的格式
            $date = date('Ymdhis');
            header('Content-Disposition: attachment;filename="提现申请'.$date.'.xlsx"');//下载下来的表格名
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            $PHPWriter->save("php://output"); //表示在$path路径下面生成demo.xlsx文件
            exit;

        }

        $rows  = $model->cashList($where);

        $total = $model->alias('a')
            ->join('users u','u.user_id = a.user_id','LEFT')
            ->join('user_account ac','ac.account_id = a.account_id','LEFT')
            ->where($where)
            ->sum('a.money');

        $this->assign([
            'getStatus' => $where['a.status'],
            'title' => '提现申请列表',
            'rows' => $rows,
            'pageHTML' => $rows->render(),
            'status' => $this->status,
            'total' => $total,
        ]);
        return view();
    }

    /**
     * 提现审核
     */
    public function edit()
    {
        $model = new Bankroll();
        if (request()->isPost()){
            $data = input('post.');
            $repeat = cache('cash_edit_repeat_'.$data['id']);
            if ($repeat){ //防止重复操作
                $this->error('请求过于频繁,请稍后重试');
            }else{
                cache('cash_edit_repeat_'.$data['id'],1,3);
            }
            $cash = $model->getDetail(['b_id'=>$data['id']]);
            if ($cash['status'] !== 2) $this->error('该申请已处理,请勿重复操作');
            $update['update_time'] = time();
            if ($data['status'] == 1){//审核通过

                switch ($cash['acType']){ //银行卡
                    case '1':

                        $update['status'] = 5;
                        Db::name('bankroll')->where('b_id',$data['id'])->update($update);

                        break;
                    case '2'://支付宝
                        //TODO 支付宝申请下来后开放自动打款
                        $update['status'] = 5;
                        Db::name('bankroll')->where('b_id',$data['id'])->update($update);
                        break;
                    default:
                        api_return(0,'未处理提现方式');
                }

            }else{//驳回
                Db::startTrans();
                try{
                    $update['status'] = 4;

                    if ($cash['use_card'] == 1){
                        $map['user_id'] = $cash['user_id'];
                        $map['type']    = 2;
                        $map['key']     = 1;
                        Db::name('my_package')->where($map)->setInc('num');
                    }

                    Db::name('bankroll')->where('b_id',$data['id'])->update($update);
                    Db::name('users')->where('user_id',$cash['user_id'])->setInc($cash['remark'],$cash['money']);


                    Db::commit();
                }catch (Exception $e){
                    Db::rollback();
                    $this->error($e->getMessage());
                }
            }

            $msg = '';
            if ($data['status'] == 1){
                $title = '同意';
                $str = sprintf('您的提现申请%s元已成功受理，预计1-2个工作日到账，请留意到账信息。如有疑问请及时与我们联系。',$cash['money']);
//                $phone = \app\api\controller\Base::staticInfo('phone',$cash['user_id']);
//
//                $val['val1'] = substr($phone,-4);
//                $val['val2'] = $cash['money'];
//                sendCustomSms($phone,$val,'cash');
            }else{
                $title = '拒绝';

                if ($data['remark']){
                    $msg = '拒绝原因为:'.$data['remark'];
                }
                $str = sprintf('您的提现申请%s元未审核通过。',$cash['money']);
                $str.=$msg;
            }

            $params =
                sprintf('%s用户[%s][user_id:%s]的提现申请;提现金额为:%s;%s',$title,$cash['nick_name'],$cash['user_id'],
                $cash['money']/100,$msg
                )
            ;
            $log['params']      = $params;
            $log['user_id']     = session('user_id');
            $log['url']         = request()->url();
            $log['title']       = '提现审核操作';
            $log['create_time'] = time();
            $log['update_time'] = time();
            $log['ip']          = request()->ip();
            Db::name('action_log')->insert($log);

            \app\api\controller\Base::sendUsrMsg('system',hashid($cash['user_id']),$str);

//            if ($data['status'] == 1){
//                $phone = \app\api\controller\Base::staticInfo('phone',$cash['user_id']);
//
//                $val['val1'] = substr($phone,-4);
//                $val['val2'] = $cash['money'];
//                sendCustomSms($phone,$val,'cash');
//            }

            $this->success('审核成功',url('cash'));

        }
        $where['a.b_id'] = input('id');
        $data = $model->getDetail($where);
        if ($data['remark'] == 'gift_coin'){

            if ($data['use_card'] == 1){
                $data['ratio'] = 0;
                $data['ratio_money'] = '提现免税卡使用';
                $data['cash']  = $data['money'];
            }else{
                //礼物收益需扣税
                $cashRatio = \app\api\controller\Base::getExtend('cash_ratio');
                $ratio = bcdiv($cashRatio,100,2);
                $data['ratio'] = $cashRatio;
                //提现手续费
                $data['ratio_money'] = bcmul($ratio,$data['money'],2);
                $data['cash'] = $data['money'] - $data['ratio_money'];
            }


        }else{
            $data['ratio'] = 0;
            $data['ratio_money'] = 0;
            $data['cash']  = $data['money'];
        }

        $this->assign([
            'title' => '提现审核',
            'data' => $data,
            'status' => $this->status,
        ]);
        return view();
    }


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 统计图表
     */
    public function map(){
        $map=[];
        if(!empty($_GET['status'])){
            $map['status']=intval(trim(input('get.status')));
        }else{
            $map['status'] = ['in','1,5'];
        }


        if(!empty($_GET['startDate'])){
            $startDate=strtotime(trim(input('get.startDate')));
        }
        if(!empty($_GET['endDate'])){
            $endDate=strtotime(trim(input('get.endDate')));
        }
        if($startDate&&$endDate){
            $map['update_time']=['between time',[$startDate,$endDate]];
        }else if($startDate&&empty($endDate)){
            $map['update_time']=['> time',$startDate];
        }else if($endDate&&empty($startDate)){
            $map['update_time']=['< time',$endDate];
        }
        $res  = Db::name('bankroll')->where($map)->field('create_time,money,status,type')->order('create_time')->select();
        $rows = [];
        foreach ($res as $k => $v){
            $date = date('Y-m-d',$v['create_time']);
            if ($v['status'] == 1){ //充值
                if(array_key_exists($date,$rows)){
                    $rows[$date]['recharge'] += $v['money'];
                }else{
                    $rows[$date]['recharge']  = $v['money'];
                    $rows[$date]['cash'] = 0;
                }
            }else{ //提现
                if(array_key_exists($date,$rows)){
                    $rows[$date]['cash'] += $v['money'];
                }else{
                    $rows[$date]['cash']  = $v['money'];
                    $rows[$date]['recharge'] = 0;
                }
            }
        }
        $recharge = json_encode(array_column($rows,'recharge'));
        $cash = json_encode(array_column($rows,'cash'));
        $days  = json_encode(array_keys($rows));
        $this->assign([
            'days'=>$days,
            'recharge'=>$recharge,
            'cash'=>$cash,
            'status'=>input('get.status')
        ]);
        return view();
    }

    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 平台资金流水
     */
    public function stream()
    {
        $where = [];

        if (!isEmpty(input('status'))){
            $where['a.status'] = input('status');
        }

        if (!isEmpty(input('money_type'))){
            $where['a.money_type'] = input('money_type');
        }


        if (!empty(input('startDate'))){
            if (empty(input('endDate'))){
                $where['a.create_time'] = ['> time',input('startDate')];
            }else{
                $where['a.create_time'] = ['between time',[input('startDate'),input('endDate')]];
            }
        }elseif (!empty(input('endDate'))){
            $where['a.create_time'] = ['<= time',input('endDate')];
        }
//        dump($where);exit;


        $model = new CapitalFlow();
        $rows  = $model->getList($where);

        $where['a.status'] = 1;
        //平台流水统计
        $stream = $model->alias('a')->where($where)->sum('money');

        //充值统计
        $where['a.status'] = 2;
        $recharge = $model->alias('a')->where($where)->sum('money');

        //提现统计
        $where['a.status'] = 3;
        $cash = $model->alias('a')->where($where)->sum('money');


        $coin = Db::name('coin')->select();
        $money_type = array_key($coin,'coin_id');
        $this->assign([
            'title' => '平台流水',
            'rows' => $rows,
            'pageHTML' => $rows->render(),
            'money_type' => $money_type,
            'status' => $this->stream_status,
            'stream' => $stream,
            'recharge' => $recharge,
            'cash' => $cash,
        ]);
        return view();
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 提现账号
     */
    public function account()
    {

        $where = [];
        if (!empty($_GET['status'])) $where['a.status']  = input('get.status');
        if (!empty($_GET['nick_name'])) $where['u.nick_name']  = ['like','%'.trim(input('get.nick_name')).'%'];
        if (is_numeric(input('uuid'))){
            $map['u.uuid'] =  ['like','%'.trim(input('get.uuid')).'%'];
        }
        $model = new UserAccount();
        $rows  = $model->getList($where);
        $this->assign([
            'title' => '充值记录',
            'rows' => $rows,
            'pageHTML' => $rows->render(),
        ]);
        return view();
    }

    public function change()
    {
        $this->_change('user_account');
    }


    public function check()
    {
        $data = input('param.');

        $item = Jewel::where('id',$data['id'])->find();

        if ($item['status'] != 1){
            $this->error('该申请已审核,请勿重复操作');
        }

        Db::startTrans();
        try{

            if($data['status'] == 1){
                $msg = '审核通过,已发放至账户余额,请注意查收';
                Db::name('users')->where('user_id',$item['user_id'])->setInc('money',$item['money']);
            }else{
                Db::name('users')->where('user_id',$item['user_id'])->setInc('spread_cash',$item['money']);

                $msg = '已被驳回!';
            }
            Db::name('jewel')->where('id',$data['id'])->update(['status'=>$data['status']]);
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }

        $str = sprintf('您的推广收益提现%s钻%s',$item['money'],$msg);
        \app\api\controller\Base::sendUsrMsg('system',hashid($item['user_id']),$str);
        $this->success('操作成功');


    }

    public function jewel()
    {
        $map = [];
        if (is_numeric($_GET['status'])){
            $map['a.status']  = input('get.status');
        }

        if (is_numeric(input('uuid'))){
            $map['u.uuid'] =  ['like','%'.trim(input('get.uuid')).'%'];
        }

        if (!empty($_GET['nick_name'])) $map['u.nick_name'] = ['like','%'.trim(input('get.nick_name')).'%'];

        if(!empty($_GET['startDate'])){
            $startDate=strtotime(trim(input('get.startDate')));
        }
        if(!empty($_GET['endDate'])){
            $endDate=strtotime(trim(input('get.endDate')));
        }
        if($startDate&&$endDate){
            $map['a.create_time']=['between time',[$startDate,$endDate]];
        }else if($startDate&&empty($endDate)){
            $map['a.create_time']=['> time',$startDate];
        }else if($endDate&&empty($startDate)){
            $map['a.create_time']=['< time',$endDate];
        }

        $model = new Jewel();
        $rows  = $model->getList($map);

        $total = $model->alias('a')
            ->join('users u','u.user_id = a.user_id','LEFT')
            ->where($map)
            ->sum('a.money');

        $this->assign([
            'title' => '提现申请列表',
            'rows' => $rows,
            'pageHTML' => $rows->render(),
            'total' => $total,
        ]);
        return view();
    }


    public static $recharge_status = [
        1=>'通过',
        0=>'拒绝',
        2=>'待审核'
    ];

    /**
     * 手动充值审核
     */
    public function recharge()
    {
        $where = [];

        if(!empty($_GET['nick_name'])){
            $where['u.nick_name|u.phone'] = ['like','%'.trim(input('get.nick_name')).'%'];
        }
        if(!empty($_GET['uuid'])){
            $where['u.uuid'] = trim(input('get.uuid'));
        }
        if(!empty($_GET['user_id'])){
            $where['u.user_id'] = trim(input('get.user_id'));
        }
        if(is_numeric($_GET['status'])){
            $where['a.status'] = trim(input('get.status'));
        }
        $model = new Recharge();
        $rows  = $model->getList($where);

        $this->assign([
            'title' => '充值申请列表',
            'rows' => $rows,
            'pageHTML' => $rows->render(),
        ]);
        return view();
    }

    /**
     * 审核
     */
    public function pass()
    {

        App::_limit(3,input('id'));

        $status = input('status');

        $data = Recharge::get(input('id'));

        if ($data['status'] != 2){
            $this->error('充值已审核,请勿重复操作');
        }
        $map['status'] = 1;
        $map['r_id']   = $data['r_id'];

        $config = RechargeConfig::where($map)->find();

        if (!$config){
            api_return(0,'系统繁忙,请稍后重试!1');
        }
        Db::startTrans();
        try{

            if ($status == 1){
                //通过
                $item['user_id'] = hashid($data['user_id']);
                $item['type']    = 'recharge';
                $item['id']      = $data['r_id'];
                $item['remark']  = '哈尼'.$config['money'].'钻充值(id:'.App::staticInfo('uuid',$data['user_id']).')';
                $item['money']   = $config['price'];
                (new \app\api\controller\Base())->recharge($item,6);
            }

            $data->save(['status'=>$status]);
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        App::_destroyLimit(input('id'));

        $this->success('操作成功');

    }
    
}